<template>
  <div class="container">
    <div class="mt-8 profile">
      <el-card shadow="hover">
        <el-form
          :model="userInfoForm"
          ref="userInfoFormRef"
          label-width="120px"
        >
          <el-descriptions
            class="margin-top"
            title="个人信息"
            :column="1"
            size="large"
            border
          >
            <template #extra>
              <el-button
                type="primary"
                :icon="Edit"
                @click="handleUpdate"
                class="bg-blue-500"
                >修改</el-button
              >

              <el-popconfirm
                confirm-button-text="是"
                cancel-button-text="否"
                title="你确定保存修改?"
                @confirm="confirmEvent"
                @cancel="cancelEvent()"
              >
                <template #reference>
                  <el-button :disabled="disable" :icon="Check">保存</el-button>
                </template>
              </el-popconfirm>
            </template>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="8">
                    <user />
                  </el-icon>
                  头像
                </div>
              </template>

              <el-upload
                class="ml-10 avatar-uploader"
                action="/api/uploadFile"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="userInfoForm.avatar"
                  :src="userInfoForm.avatar"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-descriptions-item>

            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="8">
                    <user />
                  </el-icon>
                  昵称
                </div>
              </template>

              <el-input
                v-model="userInfoForm.nickName"
                :placeholder="nickName"
                :disabled="disable"
              />
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="8">
                    <iphone />
                  </el-icon>
                  手机号
                </div>
              </template>
              <el-input
                v-model="userInfoForm.phoneNumber"
                :placeholder="phoneNumber"
                :disabled="disable"
              />
            </el-descriptions-item>

            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="8">
                    <Message />
                  </el-icon>
                  邮箱
                </div>
              </template>
              <el-input
                v-model="userInfoForm.email"
                :placeholder="email"
                :disabled="disable"
              />
            </el-descriptions-item>
          </el-descriptions>
        </el-form>
      </el-card>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Check, Edit } from "@element-plus/icons-vue";
import { updateUserInfo, getUserInfoById } from "@/api/user";
import Storage from "@/utils/Storage";

const storage = new Storage();
// 获取本地存储的用户信息
const userString = localStorage.getItem("userInfo");
const user = JSON.parse(userString);
const userInfoForm = reactive({
  nickName: "",
  email: "",
  avatar: "",
  phoneNumber: "",
});
// 在页面加载完成之后将本地存储的用户信息赋值给表单
onMounted(async () => {
  userInfoForm.nickName = user.nickName;
  userInfoForm.email = user.email;
  userInfoForm.avatar = user.avatar;
  userInfoForm.phoneNumber = user.phoneNumber;
});

const imageUrl = ref("");
const disable = ref(true);
const handleUpdate = () => {
  disable.value = !disable.value;
};

// 图片上传成功的回调函数
const handleAvatarSuccess = async (response, uploadFile) => {
  imageUrl.value = response.result;
  userInfoForm.avatar = response.result;
  console.log(response.result);
  let userAvatar = {
    id: user.id,
    avatar: response.result,
  };
  await updateUserInfo(userAvatar).then((res) => {
    if (res.code == 200) {
      // userInfoStore.setUserInfo(userId.value);
      ElMessage({
        message: "头像修改成功！",
        type: "success",
      });
      refreshUserInfo();
    }
  });
};

// 图片上传前校验函数
const beforeAvatarUpload = (rawFile) => {
  let types = ["image/jpeg", "image/jpg", "image/png"];
  const isImage = types.includes(rawFile.type);
  if (!isImage) {
    ElMessage.error("图片必须是jpg或png格式!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片不能超过2MB!");
    return false;
  }
  return true;
};

const confirmEvent = () => {
  console.log(user.id);
  let userInfo = {
    ...userInfoForm,
    id: user.id,
  };
  updateUserInfo(userInfo).then((res) => {
    if (res.code == 200) {
      ElMessage({
        message: "修改成功！",
        type: "success",
        showClose: true,
        center: true,
      });
      // 用户信息修改成功后刷新本地存储
      refreshUserInfo();
    }
  });

  disable.value = true;
};

// 更新本地存储的用户信息
const refreshUserInfo = async () => {
  await getUserInfoById(user.id).then((res) => {
    localStorage.setItem("userInfo", JSON.stringify(res.result));
  });
};
const cancelEvent = () => {
  disable.value = true;
};
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
}
.profile {
  width: 800px;
  // height: 450px;
  display: flex;
  justify-content: center;
  align-content: center;
}

.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  display: block;
  border-radius: 50px;
}
</style>
